﻿using System.Web;
using System.Web.Routing;

namespace CodeContrib.Web.Routing
{
	public class TenantRoute : LowercaseRoute
	{
		public const string HttpContextKey = "__TenantRoute";

		public TenantRoute(string url, IRouteHandler routeHandler) : base(url, routeHandler)
		{
		}

		public TenantRoute(string url, RouteValueDictionary defaults, IRouteHandler routeHandler) : base(url, defaults, routeHandler)
		{
		}

		public TenantRoute(string url, RouteValueDictionary defaults, RouteValueDictionary constraints, IRouteHandler routeHandler) : base(url, defaults, constraints, routeHandler)
		{
		}

		public TenantRoute(string url, RouteValueDictionary defaults, RouteValueDictionary constraints, RouteValueDictionary dataTokens, IRouteHandler routeHandler) : base(url, defaults, constraints, dataTokens, routeHandler)
		{
		}

		public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
		{
			var path = base.GetVirtualPath(requestContext, values);
			var tenantRoute = HttpContext.Current.Items[HttpContextKey] as TenantRouteInfo;

			if (path != null
			    && tenantRoute != null)
			{
				path.VirtualPath = tenantRoute.RewriteOutbound(path.VirtualPath);
			}

			return path;
		}
	}
}